package org.jeecg.modules.user.member.service.impl;

import com.aliyuncs.cloudauth.model.v20190307.DescribeVerifyResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.common.service.CommonMethodService;
import org.jeecg.modules.user.member.service.RealAuthService;
import org.jeecg.modules.param.member.entity.BikeMemberUser;
import org.jeecg.modules.param.member.mapper.BikeMemberUserMapper;
import org.jeecg.modules.utils.AliAuthUtils;
import org.jeecg.modules.utils.BikeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description: bike_pile
 * @Author: jeecg-boot
 * @Date:   2021-05-19
 * @Version: V1.0
 */
@Service
public class RealAuthServiceImpl implements RealAuthService {

    @Autowired
    private BikeMemberUserMapper bikeMemberUserMapper;
    @Autowired
    private CommonMethodService commonMethodService;

    @Override
    public BikeResult aliAuthen() {
        return BikeResult.ok("1","发起认证请求成功",AliAuthUtils.AliAuthen());
    }

    @Override
    public BikeResult getAliResult(String RequestId, HttpServletRequest request) {
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String phone = JwtUtil.getUsername(token);

        DescribeVerifyResultResponse describeVerifyResultResponse = AliAuthUtils.getAliResult(RequestId,request);


        if (describeVerifyResultResponse.getVerifyStatus()!=1){
            return BikeResult.error("0","认证不通过",describeVerifyResultResponse.getVerifyStatus());
        }
        Date date = new Date();// 得到当前的系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String fyear = format.format(date).substring(0, 4);// 当前年份
        String fyue = format.format(date).substring(5, 7);// 月份

        BikeMemberUser idCard = bikeMemberUserMapper.selectOne(new QueryWrapper<BikeMemberUser>().eq("id_card", describeVerifyResultResponse.getMaterial().getIdCardNumber()));
        if (idCard!=null){
          return BikeResult.error("0","您的身份证已被其他用户使用！！！",null);
        }

        QueryWrapper qw = null;
        BikeMemberUser bikeMemberUser = null;
        try {
            qw = new QueryWrapper();
            qw.eq("phone",phone);
            qw.ne("status","4");
            bikeMemberUser = new BikeMemberUser();
            bikeMemberUser.setName(describeVerifyResultResponse.getMaterial().getIdCardName());
            bikeMemberUser.setIdCard(describeVerifyResultResponse.getMaterial().getIdCardNumber());
            bikeMemberUser.setIsCertification("1");
            int age = 0;
            if (describeVerifyResultResponse.getMaterial().getIdCardNumber().length()>15){
                String year = describeVerifyResultResponse.getMaterial().getIdCardNumber().substring(6).substring(0, 4);// 得到年份
                String yue = describeVerifyResultResponse.getMaterial().getIdCardNumber().substring(10).substring(0, 2);// 得到月份
                // String day=CardCode.substring(12).substring(0,2);//得到日


                if (Integer.parseInt(describeVerifyResultResponse.getMaterial().getIdCardNumber().substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                    bikeMemberUser.setSex("2");
                } else {
                    bikeMemberUser.setSex("1");
                }

                if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
                    age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
                } else {// 当前用户还没过生
                    age = Integer.parseInt(fyear) - Integer.parseInt(year);
                }
                bikeMemberUser.setAge(age);
            }else {
                String uyear = "19" + describeVerifyResultResponse.getMaterial().getIdCardNumber().substring(6, 8);// 年份
                String uyue = describeVerifyResultResponse.getMaterial().getIdCardNumber().substring(8, 10);// 月份
                String usex = describeVerifyResultResponse.getMaterial().getIdCardNumber().substring(14, 15);// 用户的性别
                if (Integer.parseInt(usex) % 2 == 0) {

                    bikeMemberUser.setSex("2");
                } else {
                    bikeMemberUser.setSex("1");
                }
                if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) { // 当前月份大于用户出身的月份表示已过生
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
                } else {// 当前用户还没过生
                    age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
                }
                bikeMemberUser.setAge(age);
            }
//            bikeMemberUser.setAddress(describeVerifyResultResponse.getMaterial().getIdCardInfo().getAddress());
//            bikeMemberUser.setStartDate(format.parse(describeVerifyResultResponse.getMaterial().getIdCardInfo().getStartDate()));
//            bikeMemberUser.setEndDate(format.parse(describeVerifyResultResponse.getMaterial().getIdCardInfo().getEndDate()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = bikeMemberUserMapper.update(bikeMemberUser,qw);
        //调整所有用户身份证后1位x转为X
        ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    commonMethodService.updateIdCard();
                    Thread.interrupted();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    Thread.interrupted();
                }
            }
        });
        return BikeResult.ok("1","实名认证成功",i);

    }
}
